/*
 * @Author: Wangtao
 * @Date: 2020-09-28 10:59:02
 * @LastEditors: zhanwang
 * @LastEditTime: 2021-06-01 10:58:36
 */
/**
 * Created by liyl on 24/09/2020.
 */
import { VuexModule, Module, Action, Mutation, getModule } from 'vuex-module-decorators'
import { commonAction, deepClone } from '@/utils/common'
import { SocketModule } from '@/store/modules/socket'
import { CommonModule } from '@/store/modules/common'
import { WebchatModule } from '@/store/modules/webchat'
// import { OemModule } from '@/store/modules/oem'
import WebPhoneSdk from '@/utils/webPhoneSdk'
import { Base64 } from 'js-base64'
import NodeRSA from 'node-rsa'
import store from '@/store'

@Module({ dynamic: true, name: 'login', store, namespaced: false })
class Login extends VuexModule {
  public webRtcFun: any = null

  @Mutation
  public setWebRtcFun (data: any) {
    this.webRtcFun = data
  }

  @Action
  public async LoginCommonAction (parame: object) {
    return commonAction(parame).then(resp => {
      return resp
    })
  }

  @Action
  public async SignIn (parame: any) {
    const actionData = { url: '/auth/login/pre', method: 'GET', data: {} }
    return commonAction(actionData).then(preResp => {
      if (preResp && preResp.success) {
        CommonModule.setPreLogin(preResp.data || {}) // 登录前获取的信息
      }
      const localFrom = parame.form
      const webchatStatus = deepClone(parame.webchatStatus)
      let encrypted = parame.encrypted
      if (!encrypted) {
        const pk = Base64.decode(preResp.data ? preResp.data.pk : '')
        const key = new NodeRSA(pk)
        encrypted = key.encrypt(parame.form.password, 'base64')
      }
      if (localFrom.remember) {
        localFrom.password = encrypted
      } else {
        localFrom.password = ''
      }
      const statusNumber = parame.form.loginStatus ? '0' : '1'
      const loadingPane = document.getElementById('v7_body')
      const lastData = { loginName: parame.form.loginName, password: encrypted, loginType: parame.form.loginType || 'WEBRTC', loginStatus: [{ statusName: 'call', statusNumber }], domain: parame.domain }
      return commonAction({ url: '/auth/login', method: 'POST', data: lastData }).then(resp => {
        if (resp && resp.success) {
          window.localStorage.setItem('loginForm', JSON.stringify(localFrom))
          window.localStorage.setItem('webchatStatus', JSON.stringify(webchatStatus))
          window.sessionStorage.setItem('sessionForm', JSON.stringify(localFrom))
          const resData = resp.data || {}
          CommonModule.setSession(resData) // 设置session信息
          const extraConfig: any = resData.extra ? resData.extra.extraConfig : {}
          if (parame.isConnectSocket) { // 普通登录 && session登录都是默认true, token登录是后台返回的配置
            SocketModule.initSocket({ data: resp.data, isLogin: parame.isLogin, webchatStatus }) // 注册socket
          }
          if (parame.isConnectWebRtc && lastData.loginType === 'WEBRTC') { // webRtc登录的，初始化个人信息
            try {
              const webPhone = new WebPhoneSdk({ server: extraConfig.sipRegisterAddress, sip: resData.user.webrtcSipNumber, secret: resData.user.webrtcSipKey })
              this.setWebRtcFun(webPhone)
            } catch (error) {
              console.log(error)
            }
          }
          // 获取在线emoji配置
          CommonModule.publicAction({ url: '/im-center/action/webchat/getEmojiConfig', method: 'POST' }).then(emoji => {
            if (emoji && emoji.success && emoji.data) {
              WebchatModule.SET_EMOJICONFIG(emoji.data)
            }
          })
          commonAction({ url: '/base/action/general/dk/get', method: 'GET', data: {} }).then(res => {
            if (res && res.success && res.data.dk) {
              CommonModule.SET_DK(res.data.dk)
            }
          })
          const commonTypes = ['userList', 'queueList', 'loginMenuList', 'commonAppIdList', 'departmentList'] // 座席，技能组列表，一级菜单列表
          const p1 = commonAction({ url: '/base/action/general/cache/query', method: 'POST', data: { types: commonTypes } }) // 通用的基础缓存
          return Promise.all([p1, CommonModule.getDepartmentTree()]).then(([commonRes]) => {
            commonTypes.forEach((item: string) => {
              let hasObj = true
              if (item === 'loginMenuList') {
                hasObj = false
              }
              CommonModule.setPublicCache({ data: commonRes[item] ? commonRes[item] : [], type: item, hasObj })
            })
            if (loadingPane) {
              loadingPane.className = ''
            }
            return resp
          })
        } else {
          if (loadingPane) {
            loadingPane.className = ''
          }
          return resp
        }
      })
    })
  }

  @Action
  public async SignInBySessionId (data: any) {
    const actionOne = commonAction({ url: '/auth/login/billJumpLogin', method: 'POST', data })
    const actionTwo = commonAction({ url: '/auth/login/pre', method: 'GET', data: {} })
    return Promise.all([actionOne, actionTwo]).then(([resp, preResp]) => {
      if (preResp && preResp.success) {
        CommonModule.setPreLogin(preResp.data || {}) // 登录前获取的信息
      }
      const loadingPane = document.getElementById('v7_body')
      if (resp && resp.success) {
        CommonModule.setSession(resp.data || {}) // 设置session信息
        SocketModule.initSocket({ data: resp.data, isLogin: data.isLogin }) // 注册socket
        // 获取在线emoji配置
        CommonModule.publicAction({ url: '/im-center/action/webchat/getEmojiConfig', method: 'POST' }).then(emoji => {
          if (emoji && emoji.success && emoji.data) {
            WebchatModule.SET_EMOJICONFIG(emoji.data)
          }
        })
        commonAction({ url: '/base/action/general/dk/get', method: 'GET', data: {} }).then(res => {
          if (res && res.success && res.data.dk) {
            CommonModule.SET_DK(res.data.dk)
          }
        })
        const commonTypes = ['userList', 'queueList', 'loginMenuList', 'commonAppIdList'] // 座席，技能组列表，一级菜单列表
        const p1 = commonAction({ url: '/base/action/general/cache/query', method: 'POST', data: { types: commonTypes } }) // 通用的基础缓存
        return Promise.all([p1, CommonModule.getDepartmentTree()]).then(([commonRes]) => {
          commonTypes.forEach((item: string) => {
            let hasObj = true
            if (item === 'loginMenuList') {
              hasObj = false
            }
            CommonModule.setPublicCache({ data: commonRes[item] ? commonRes[item] : [], type: item, hasObj })
          })
          if (loadingPane) {
            loadingPane.className = ''
          }
          return resp
        })
      } else {
        if (loadingPane) {
          loadingPane.className = ''
        }
        return resp
      }
    })
  }

  @Action
  public async SignInByToken (data: any) {
    const actionOne = commonAction({ url: '/auth/login/pre', method: 'GET', data: {} })
    const actionTwo = commonAction({ url: '/auth/login/token', method: 'POST', data })
    return Promise.all([actionOne, actionTwo]).then(([preResp, resp]) => {
      if (preResp && preResp.success) {
        CommonModule.setPreLogin(preResp.data || {}) // 登录前获取的信息
      }
      const loadingPane = document.getElementById('v7_body')
      if (resp && resp.success) {
        const resData = resp.data || {}
        window.localStorage.setItem('loginForm', JSON.stringify({ loginType: resData.loginType || 'WEBRTC' }))
        window.localStorage.setItem('webchatStatus', JSON.stringify(resData.webchatStatus))
        CommonModule.setSession(resData) // 设置session信息
        const extraConfig: any = resData.extra ? resData.extra.extraConfig : {}
        if (resData.isConnectSocket) { // 普通登录 && session登录都是默认true, token登录是后台返回的配置
          SocketModule.initSocket({ data: resData, isLogin: true, webchatStatus: resData.webchatStatus }) // 注册socket
        }
        if (resData.isConnectWebRtc && resData.loginType === 'WEBRTC') { // webRtc登录的，初始化个人信息
          try {
            const webPhone = new WebPhoneSdk({ server: extraConfig.sipRegisterAddress, sip: resData.user.webrtcSipNumber, secret: resData.user.webrtcSipKey })
            this.setWebRtcFun(webPhone)
          } catch (error) {
            console.log(error)
          }
        }
        // 获取在线emoji配置
        CommonModule.publicAction({ url: '/im-center/action/webchat/getEmojiConfig', method: 'POST' }).then(emoji => {
          if (emoji && emoji.success && emoji.data) {
            WebchatModule.SET_EMOJICONFIG(emoji.data)
          }
        })
        commonAction({ url: '/base/action/general/dk/get', method: 'GET', data: {} }).then(res => {
          if (res && res.success && res.data.dk) {
            CommonModule.SET_DK(res.data.dk)
          }
        })
        const commonTypes = ['userList', 'queueList', 'loginMenuList', 'commonAppIdList'] // 座席，技能组列表，一级菜单列表
        const p1 = commonAction({ url: '/base/action/general/cache/query', method: 'POST', data: { types: commonTypes } }) // 通用的基础缓存
        return Promise.all([p1, CommonModule.getDepartmentTree()]).then(([commonRes]) => {
          commonTypes.forEach((item: string) => {
            let hasObj = true
            if (item === 'loginMenuList') {
              hasObj = false
            }
            CommonModule.setPublicCache({ data: commonRes[item] ? commonRes[item] : [], type: item, hasObj })
          })
          if (loadingPane) {
            loadingPane.className = ''
          }
          return resp
        })
      } else {
        if (loadingPane) {
          loadingPane.className = ''
        }
        return resp
      }
    })
  }
}

export const LoginModule = getModule(Login)
